import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 是否显示底部导航栏  默认显示
    showBottomBar: true,
    // 添加到购物车的数据
    car: [],
    // goodsCount代表购物车商品的数量
    goodsCount: 0
  },
  mutations: {
    changeShowBottomBar (state, i) {
      if (i === 2) {
        state.showBottomBar = false
      } else {
        state.showBottomBar = true
      }
    },
    // 页面一加载  就从localStorage中取出数据  存储在car中
    saveInCar (state) {
      if (window.localStorage.getItem('car') !== null) {
        state.car = JSON.parse(window.localStorage.getItem('car'))
      } else {
        state.car = []
      }
    },
    // 获取购物车商品的数量
    getCartCount (state) {
      // 先清零
      state.goodsCount = 0
      const arr = JSON.parse(window.localStorage.getItem('car'))
      console.log(arr)
      // 如果购物车中没数据
      if (arr === null) {
        state.goodsCount = 0
      } else {
        arr.forEach(ele => {
          state.goodsCount += ele.count
        })
      }
    }
  },
  actions: {
  },
  modules: {
  }
})
